

public class MyQuickSort {

	  int[] iVector =  { 18, 4, 7, 54, 8, 563, 3, 5, 568,4, 9, 76, 6, 4};
	  int iStart = 0, iEnd = iVector.length - 1, iLeft = iStart,
			iPivot = iStart, iRight = iEnd;

	public  void main(String[] args) {
		
		long start, stop;
		start = System.nanoTime();
		Sort(iLeft, iRight);
		stop = System.nanoTime();
		System.out.println("TEMPO: " + (stop - start) + " nanosegs");
		printVector();
		
	}
	public void Sort(int iStart, int iEnd) {
		iLeft = iStart;
		iRight = iEnd;
		iPivot = iStart;
		
		if (iStart < iEnd) {

			verifSwap();
			
			Sort(iStart, iPivot-1);
			Sort(iPivot+1, iEnd);
		}
	}
	public void verifSwap() {

		seekSwap();

		if (iLeft != iPivot && iRight != iPivot) {
			
			swapLeftRight();
			verifSwap();

		} else if (iLeft != iPivot && iRight == iPivot) {

			definePartition();
			verifSwap();

		} else if (iLeft == iPivot && iRight != iPivot) {

			definePartition();
			verifSwap();

		} else {

			//DEFINE NOVA PARTICAO VIA RECURCAO.
		}

	}
	public void definePartition() {
		int iTempPivot;

		if (iRight > iPivot)
			iTempPivot = iPivot + ((iRight - iLeft + 1) / 2);
		else
			iTempPivot = iPivot - ((iRight - iLeft + 1) / 2);

		int iTempPivotVal = iVector[iTempPivot];

		iVector[iTempPivot] = iVector[iPivot];
		iVector[iPivot] = iTempPivotVal;
		iPivot = iTempPivot;
	}
	public void seekSwap() {

		iLeftSwapIndex();
		iRightSwapIndex();
		
	}
	public void printVector() {
		
		for (int i = 0; i < iVector.length; i++) {
			System.out.print(iVector[i] + ",");
			
		}
	}
	public  void swapLeftRight() {

		int temp = iVector[iLeft];
		iVector[iLeft] = iVector[iRight];
		iVector[iRight] = temp;

	}
	public int iLeftSwapIndex() {
		if (iLeft == iPivot) {
			return iLeft;
		}

		if (iVector[iLeft] > iVector[iPivot])
			return iLeft;
		else
			++iLeft;
		return iLeftSwapIndex();

	}
	public int iRightSwapIndex() {
		if (iRight == iPivot) {
			return iRight;
		}

		if (iVector[iRight] < iVector[iPivot])
			return iRight;
		else
			--iRight;
		return iRightSwapIndex();
	}
}
